package com.tonny.tweet.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.tonny.tweet.dao.TweetDao;
import com.tonny.tweet.model.Tweet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class TweetDaoImpl implements TweetDao {
    @Autowired
    private JdbcTemplate template;
    
    @Override
    public int insert(Tweet tweet) {
        return template.update("INSERT INTO tweet(user_id, content, status) VALUES(?, ?, ?)", tweet.getUserId(), tweet.getContent(),
                               tweet.getStatus());
    }
    
    @Override
    public List<Tweet> queryByUserId(long userId, int status, int offset, int limit) {
        return template.query("SELECT * FROM tweet WHERE user_id = ? AND status = ? ORDER BY id DESC limit ?, ?",
                              new Object[]{userId, status, offset, limit}, new RowMapper<Tweet>() {
                    @Override
                    public Tweet mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return parseTo(rs);
                    }
                });
    }
    
    private Tweet parseTo(ResultSet rs) throws SQLException {
        Tweet tweet = new Tweet();
        tweet.setId(rs.getLong("id"));
        tweet.setCreateTime(rs.getTimestamp("create_time"));
        tweet.setUpdateTime(rs.getTimestamp("update_time"));
        tweet.setContent(rs.getString("content"));
        tweet.setStatus(rs.getInt("status"));
        tweet.setUserId(rs.getLong("user_id"));
        return tweet;
    }
    
    @Override
    public long countByUserId(long userId) {
        return template.queryForObject("select count(*) from tweet where user_id = ?", new Object[]{userId}, Long.class);
    }
    
    @Override
    public Tweet queryById(long tweetId) {
        try {
            return template.queryForObject("select * from tweet where id = ?", new Object[]{tweetId}, new RowMapper<Tweet>() {
                @Override
                public Tweet mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return parseTo(rs);
                }
            });
        }
        catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    @Override
    public int updateStatus(long tweetId, Integer status) {
        return template.update("UPDATE tweet SET status = ? WHERE id = ?", new Object[]{status, tweetId});
    }
}
